package cn.bjit.service.impl;

import cn.bjit.enums.BizCodeEnum;
import cn.bjit.enums.SendCodeEnum;
import cn.bjit.feign.CouponFeignService;
import cn.bjit.interceptor.LoginInterceptor;
import cn.bjit.mapper.UserMapper;
import cn.bjit.model.LoginUser;
import cn.bjit.model.UserDO;
import cn.bjit.request.NewUserCouponRequest;
import cn.bjit.request.UserLoginRequest;
import cn.bjit.request.UserRegisterRequest;
import cn.bjit.service.NotifyService;
import cn.bjit.service.UserService;
import cn.bjit.util.CommonUtil;
import cn.bjit.util.JWTUtil;
import cn.bjit.util.JsonData;
import cn.bjit.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private NotifyService notifyService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private CouponFeignService couponFeignService;

    /**
     * 用户注册功能
     * 1,邮箱验证码验证
     * 2,密码加密（TODO）
     * 3,账号唯一性检查(TODO)
     * 4,插入数据库
     * 5,新注册用户福利发放(TODO)
     *
     * @param registerRequest
     * @return
     */
    //@Transactional(rollbackFor=Exception.class,propagation= Propagation.REQUIRED)
    //@GlobalTransactional
    public JsonData register(UserRegisterRequest registerRequest) {
        boolean checkCode = false;
        if (StringUtils.isNotBlank(registerRequest.getMail())) {
            checkCode = notifyService.checkCode(SendCodeEnum.USER_REGISTER, registerRequest.getMail(), registerRequest.getCode());
        }
        if (!checkCode) {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(registerRequest, userDO);

        userDO.setCreateTime(new Date());
        userDO.setSlogan("相信相信的力量");
        //设置密码
        //userDO.setPwd(registerRequest.getPwd());
        //生成秘钥  盐            $1$ABCadadadadada     //adadadadada $1$ABC
        userDO.setSecret("$1$" + CommonUtil.getStringNumRandom(8));
        //密码+盐处理
        String cryptPwd = Md5Crypt.md5Crypt(registerRequest.getPwd().getBytes(), userDO.getSecret());
        userDO.setPwd(cryptPwd);

        //账号唯一性检查
        if (checkUnique(userDO.getMail())) {
            int rows = userMapper.insert(userDO);
            log.info("rows:{},注册成功:{}", rows, userDO.toString());
            //新用户注册成功，初始化信息，发放福利等 TODO
            userRegisterInitTask(userDO);
            //模拟异常测试seata
//            int x=1/0;
            return JsonData.buildSuccess();
        } else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_REPEAT);
        }
    }

    /**
     * 用户登录
     * 1、根据Mail去找有没这记录
     * 2、有的话，则用秘钥+用户传递的明文密码，进行加密，再和数据库的密文进行匹配
     *
     * @param userLoginRequest
     * @return
     */
    @Override
    public JsonData login(UserLoginRequest userLoginRequest) {
        List<UserDO> userDOList = userMapper.selectList(new QueryWrapper<UserDO>().eq("mail", userLoginRequest.getMail()));
        if (userDOList != null && userDOList.size() == 1) { //查到了
            UserDO userDO = userDOList.get(0);//获取查到的用户
            String pwdCrypt = Md5Crypt.md5Crypt(userLoginRequest.getPwd().getBytes(), userDO.getSecret());

            if (pwdCrypt.equals(userDO.getPwd())) {
                //登录成功,生成token
                LoginUser loginUser = new LoginUser();
                BeanUtils.copyProperties(userDO, loginUser);
                String token = JWTUtil.geneJsonWebToken(loginUser);

                return JsonData.buildSuccess(token);
            } else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);//账号或者密码错误
            }
        } else {//没查到 未注册
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER); //账号不存在
        }
    }


    /**
     * 查找用户详情
     *
     * @return
     */
    @Override
    public UserVO findUserDetail() {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        UserDO userDO = userMapper.selectOne(new QueryWrapper<UserDO>().eq("id", loginUser.getId()));
        UserVO userVo=new UserVO();
        BeanUtils.copyProperties(userDO,userVo);
        return userVo;
    }


    /**
     * 校验用户账号唯一
     *
     * @param mail
     * @return
     */
    private boolean checkUnique(String mail) {
        QueryWrapper queryWrapper = new QueryWrapper<UserDO>().eq("mail", mail);
        List list = userMapper.selectList(queryWrapper);
        return list.size() > 0 ? false : true;
    }

    /**
     * 用户注册，初始化福利信息 TODO
     * @param userDO
     */
    private void userRegisterInitTask(UserDO userDO) {
        NewUserCouponRequest request = new NewUserCouponRequest();
        request.setName(userDO.getName());
        request.setUserId(userDO.getId());
        JsonData jsonData = couponFeignService.addNewUserCoupon(request);
//        if(jsonData.getCode()!=0){
//           throw  new RuntimeException("发送优惠券异常！");
//        }
        log.info("发放新用户注册优惠券：{},结果:{}",request.toString(),jsonData.toString());

    }
}